<template>
  <div class="foster-reserve-container">
    <div class="page-header">
      <h1>🏠 宠物寄养预约</h1>
      <p>安全舒适的寄养环境，让您的爱宠有个温馨的家</p>
    </div>

    <!-- 寄养须知 -->
    <el-alert
      title="寄养须知"
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;">
      <div>
        <p>1. 寄养需提前预约，确保有充足的位置</p>
        <p>2. 请确保宠物已接种疫苗并提供健康证明</p>
        <p>3. 寄养期间我们会定期向您反馈宠物状况</p>
        <p>4. 建议带上宠物熟悉的物品（玩具、毛毯等）</p>
      </div>
    </el-alert>

    <!-- 我的寄养记录 -->
    <el-card class="foster-list-card">
      <div slot="header">
        <span>我的寄养记录</span>
        <el-button type="primary" size="small" style="float: right" @click="showReserveDialog">
          <i class="el-icon-plus"></i> 新建寄养
        </el-button>
      </div>

      <el-table :data="fosterList" v-loading="loading">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="宠物名称">{{ props.row.petName }}</el-descriptions-item>
              <el-descriptions-item label="宠物品种">{{ props.row.petBreed }}</el-descriptions-item>
              <el-descriptions-item label="入住时间">{{ props.row.startDate }}</el-descriptions-item>
              <el-descriptions-item label="预计离店">{{ props.row.endDate }}</el-descriptions-item>
              <el-descriptions-item label="寄养天数">{{ props.row.days }}天</el-descriptions-item>
              <el-descriptions-item label="每日费用">¥{{ props.row.pricePerDay }}/天</el-descriptions-item>
              <el-descriptions-item label="总费用">
                <span class="price">¥{{ props.row.totalPrice }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ props.row.phone }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">{{ props.row.remark || '无' }}</el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <el-table-column prop="petName" label="宠物名称"></el-table-column>
        <el-table-column prop="startDate" label="入住时间"></el-table-column>
        <el-table-column prop="endDate" label="预计离店"></el-table-column>
        <el-table-column prop="days" label="天数">
          <template slot-scope="scope">
            {{ scope.row.days }}天
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="总费用">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.totalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleViewDetail(scope.row)">
              详情
            </el-button>
            <el-button size="mini" type="danger" @click="handleCancel(scope.row)"
                       v-if="scope.row.status === '待确认'">
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 寄养环境展示 -->
    <el-card class="environment-card" style="margin-top: 20px;">
      <div slot="header">
        <span>寄养环境</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="6" v-for="env in environments" :key="env.id">
          <div class="env-item">
            <img :src="env.image" class="env-image">
            <h4>{{ env.title }}</h4>
            <p>{{ env.description }}</p>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 预约寄养对话框 -->
    <el-dialog title="宠物寄养预约" :visible.sync="reserveDialogVisible" width="700px">
      <el-form :model="reserveForm" :rules="reserveRules" ref="reserveForm" label-width="120px">
        <el-form-item label="选择宠物" prop="petId">
          <el-select v-model="reserveForm.petId" placeholder="请选择宠物" style="width: 100%">
            <el-option v-for="pet in myPets" :key="pet.id" :label="pet.name" :value="pet.id">
              <span>{{ pet.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ pet.breed }} | {{ pet.age }}个月
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="寄养时间" prop="dateRange">
          <el-date-picker
            v-model="reserveForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="入住日期"
            end-placeholder="离店日期"
            style="width: 100%"
            :picker-options="pickerOptions"
            @change="calculateDays">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="寄养天数">
          <el-input v-model="reserveForm.days" disabled>
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每日费用">
          <el-input v-model="pricePerDay" disabled>
            <template slot="append">元/天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="总费用">
          <el-input :value="totalPrice" disabled>
            <template slot="prepend">¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="reserveForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="特殊需求">
          <el-input type="textarea" v-model="reserveForm.remark"
                    :rows="3" placeholder="请输入特殊需求或备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="reserveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReserve">确认预约</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMyFosterRecords, createFosterReserve, cancelFosterReserve, getFosterInfo } from '@/api/foster'
import { getMyPets } from '@/api/user'

export default {
  name: 'FosterReserve',
  data () {
    return {
      loading: false,
      fosterList: [],
      myPets: [],
      reserveDialogVisible: false,
      pricePerDay: 100,
      reserveForm: {
        petId: null,
        dateRange: null,
        days: 0,
        phone: '',
        remark: ''
      },
      reserveRules: {
        petId: [{ required: true, message: '请选择宠物', trigger: 'change' }],
        dateRange: [{ required: true, message: '请选择寄养时间', trigger: 'change' }],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      environments: []
    }
  },
  computed: {
    totalPrice () {
      return this.reserveForm.days * this.pricePerDay
    }
  },
  created () {
    this.loadFosterInfo()
    this.loadMyPets().then(() => {
      this.loadFosterList()
    })
    this.loadEnvironments()
  },
  methods: {
    loadFosterInfo () {
      getFosterInfo().then(res => {
        if (res && res.data) {
          this.pricePerDay = res.data.pricePerDay || 100
        }
      }).catch(err => {
        console.error('加载寄养信息失败：', err)
      })
    },
    loadFosterList () {
      this.loading = true
      getMyFosterRecords({
        pageNum: 1,
        pageSize: 100
      }).then(res => {
        this.loading = false
        console.log('寄养记录响应数据：', res)
        if (res && res.data) {
          const data = res.data.records || res.data.list || res.data || []
          console.log('解析后的数据数组：', data)
          this.fosterList = data.map(item => {
            console.log('单条记录：', item)
            return {
              id: item.id,
              reservationNo: item.reservationNo,
              petId: item.petId,
              petName: item.petName || '未知',
              petBreed: item.petBreed || '未知',
              startDate: item.startDate || item.reservationDate || '',
              endDate: item.endDate || item.reservationDate || '',
              reservationTime: item.reservationTime || '',
              days: item.days || 1,
              pricePerDay: item.pricePerDay || this.pricePerDay,
              totalPrice: item.totalPrice || item.totalAmount || 0,
              phone: item.phone || '',
              remark: item.remark || item.specialRequirements || '',
              status: item.status || this.getStatusText(item.reservationStatus)
            }
          })
          console.log('最终的fosterList：', this.fosterList)
        }
      }).catch(err => {
        this.loading = false
        console.error('加载寄养记录失败：', err)
        this.$message.error({ message: '加载寄养记录失败', duration: 800 })
      })
    },
    loadMyPets () {
      return getMyPets().then(res => {
        if (res && res.data) {
          const data = res.data.list || res.data || []
          this.myPets = data.map(item => ({
            id: item.id,
            name: item.name,
            breed: item.breed || '',
            age: item.age || 0
          }))
        }
      }).catch(err => {
        console.error('加载我的宠物失败：', err)
      })
    },
    getStatusText (status) {
      const statusMap = {
        0: '待确认',
        1: '已确认',
        2: '寄养中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '待确认'
    },
    loadEnvironments () {
      this.environments = [
        { id: 1, title: '独立房间', description: '宽敞舒适的独立空间', image: '' },
        { id: 2, title: '活动区域', description: '室内外活动场地', image: '' },
        { id: 3, title: '专业护理', description: '24小时专人照看', image: '' },
        { id: 4, title: '健康监测', description: '定期健康检查', image: '' }
      ]
    },
    showReserveDialog () {
      this.reserveForm = {
        petId: null,
        dateRange: null,
        days: 0,
        phone: '',
        remark: ''
      }
      this.reserveDialogVisible = true
    },
    calculateDays () {
      if (this.reserveForm.dateRange && this.reserveForm.dateRange.length === 2) {
        const start = new Date(this.reserveForm.dateRange[0])
        const end = new Date(this.reserveForm.dateRange[1])
        const diffTime = Math.abs(end - start)
        this.reserveForm.days = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      } else {
        this.reserveForm.days = 0
      }
    },
    submitReserve () {
      this.$refs.reserveForm.validate((valid) => {
        if (valid) {
          const startDate = new Date(this.reserveForm.dateRange[0])
          const reservationDateStr = startDate.toISOString().split('T')[0]
          const totalAmount = this.reserveForm.days * this.pricePerDay
          createFosterReserve({
            petId: this.reserveForm.petId,
            serviceTypeId: 1,
            reservationDate: reservationDateStr,
            reservationTime: '10:00:00',
            specialRequirements: this.reserveForm.remark || '',
            totalAmount: totalAmount
          }).then(res => {
            this.$message.success({ message: '预约成功！', duration: 800 })
            this.reserveDialogVisible = false
            this.loadFosterList()
          }).catch(err => {
            console.error('预约失败：', err)
            this.$message.error({ message: '预约失败', duration: 800 })
          })
        }
      })
    },
    handleViewDetail (row) {
      this.$router.push({ path: '/user/foster-detail', query: { id: row.id } })
    },
    handleCancel (row) {
      this.$confirm('确认取消该寄养预约吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelFosterReserve(row.id).then(res => {
          this.$message.success({ message: '已取消预约', duration: 800 })
          this.loadFosterList()
        }).catch(err => {
          console.error('取消预约失败：', err)
          this.$message.error({ message: '取消预约失败', duration: 800 })
        })
      })
    },
    getStatusType (status) {
      const typeMap = {
        '待确认': 'warning',
        '已确认': 'primary',
        '寄养中': 'success',
        '已完成': 'info',
        '已取消': 'danger'
      }
      return typeMap[status] || 'info'
    }
  }
}
</script>

<style scoped>
.foster-reserve-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 30px;
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  color: white;
  border-radius: 8px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 32px;
}

.foster-list-card {
  margin-bottom: 20px;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.env-item {
  text-align: center;
  margin-bottom: 20px;
}

.env-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 10px;
}

.env-item h4 {
  margin: 10px 0;
  color: #333;
}

.env-item p {
  color: #666;
  font-size: 14px;
}
</style>
